﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using AutoMapper;
using SapaFinance.DTO;
using SapaFinance.Domain.Model;
using SapaFinance.GenericRepository;

namespace SapaFinance.Services
{
    public interface IBudgetItemService
    {
        IEnumerable<AbstractDTO> GetListDTO();
        IEnumerable<SelectListItem> GetSelectedListById(Guid id);
        void Insert(BudgetItemDTO dto);
        void Delete(Guid id);
        void Update(BudgetItemDTO dto);
        BudgetItem GetBudgetItem(Guid id);
    }

    public class BudgetItemService : IBudgetItemService
    {
        private readonly IGenericRepository<BudgetItem, Guid> _budgetItemRepository;
        private readonly IMappingEngine _mappingEngine;
        private readonly IEntityFactory _entityFactory;
        private readonly IUnitOfWork _unitOfWork;

        public BudgetItemService(IGenericRepository<BudgetItem, Guid> budgetItemRepository, IUnitOfWork unitOfWork, IMappingEngine mappingEngine, IEntityFactory entityFactory)
        {
            _budgetItemRepository = budgetItemRepository;
            _unitOfWork = unitOfWork;
            _mappingEngine = mappingEngine;
            _entityFactory = entityFactory;
        }

        #region IBudgetItemService Members

        public virtual IEnumerable<AbstractDTO> GetListDTO()
        {
            return _mappingEngine.Map<IEnumerable<BudgetItem>, List<BudgetItemDTO>>(_budgetItemRepository.GetAll());
        }

        public virtual IEnumerable<SelectListItem> GetSelectedListById(Guid id)
        {
            return Guid.Empty.Equals(id)
                       ? _mappingEngine.Map<IEnumerable<BudgetItem>, List<SelectListItem>>(_budgetItemRepository.GetAll())
                       : _mappingEngine.Map<BudgetItem, IEnumerable<SelectListItem>>(_budgetItemRepository.GetById(id));
        }

        public void Insert(BudgetItemDTO dto)
        {
            var entity = _entityFactory.BuildBudgetItem(dto);
            _budgetItemRepository.Insert(entity);
            _unitOfWork.Flush();
        }

        public void Delete(Guid id)
        {
            var entity = _budgetItemRepository.GetById(id);
            _budgetItemRepository.Delete(entity);
            _unitOfWork.Flush();
        }

        public void Update(BudgetItemDTO dto)
        {
            var budgetItem = _budgetItemRepository.GetById(dto.UID);
            budgetItem.Name = dto.Name;
            _budgetItemRepository.Update(budgetItem);
            _unitOfWork.Flush();
        }

        public BudgetItem GetBudgetItem(Guid id)
        {
            return _budgetItemRepository.GetById(id);
        }

        #endregion
    }
}